package com.gf.framework.common.model.user;

import org.bson.types.ObjectId;

import java.util.Optional;

/**
 * @author gaofei
 * @date 2022/5/27 22:17
 * 用户上下文信息
 */
public class UserContext {

    private static final ThreadLocal<UserLoginInfo> USER_THREAD_LOCAL = new ThreadLocal<>();

    public static void set(UserLoginInfo user) {
        USER_THREAD_LOCAL.set(user);
    }

    public static UserLoginInfo get() {
        return USER_THREAD_LOCAL.get();
    }

    public static boolean isLogin() {
        return Optional.ofNullable(USER_THREAD_LOCAL.get()).isPresent();
    }

    public static Long getUserId() {
        return getUserIdOrNull();
    }

    public static Long getUserIdOrNull() {
        Optional<UserLoginInfo> optional = Optional.ofNullable(USER_THREAD_LOCAL.get());
        return optional.map(UserLoginInfo::getId).orElse(null);
    }

    public static Long getUserIdOrDefault() {
        Optional<UserLoginInfo> optional = Optional.ofNullable(USER_THREAD_LOCAL.get());
        return optional.map(UserLoginInfo::getId).orElse(null);
    }

    public static void remove() {
        USER_THREAD_LOCAL.remove();
    }
}